package com.government.quartz.task;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.government.member.domain.VipOrder;
import com.government.member.service.VipOrderService;
import com.government.wxpay.service.WxPayService;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Component("wxPayTask")
@Transactional(rollbackFor = Exception.class)
public class WxpayTask {

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private VipOrderService vipOrderService;

    public void wxPayStatusHandler() {
        List<VipOrder> vipOrderList = vipOrderService.selectUnpaidVipOrder();
        for (VipOrder vipOrder : vipOrderList) {
            Transaction transaction;
            if ("NATIVE".equals(vipOrder.getTradeType())) {
                transaction = wxPayService.nativePayStatus(vipOrder.getOutTradeNo());
            } else {
                transaction = wxPayService.jsapiPayStatus(vipOrder.getOutTradeNo());
            }
            if (Transaction.TradeStateEnum.SUCCESS.name().equals(transaction.getTradeState().name())) {
                vipOrder.setPaySuccessAmount(new BigDecimal(transaction.getAmount().getTotal()).divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP));
                vipOrder.setOrderStatus(1);
                vipOrder.setPayStatus(1);
                vipOrder.setUpdateTime(new Date());
                vipOrder.setPayTime(DateUtil.parseDateTime(transaction.getSuccessTime().substring(0, transaction.getSuccessTime().indexOf("+")).replace("T", " ")));
                vipOrder.setTradeType(transaction.getTradeType().name());
                vipOrder.setTransactionId(transaction.getTransactionId());
                vipOrderService.updateVipOrder(vipOrder);
                wxPayService.vipInfoHandler(vipOrder);
            } else {
                if (DateUtil.between(vipOrder.getCreateTime(), DateUtil.date(), DateUnit.HOUR, true) >= 2) {
                    if ("NATIVE".equals(vipOrder.getTradeType())) {
                        wxPayService.closeNativePrepay(vipOrder.getOutTradeNo());
                    } else {
                        wxPayService.closeJsapiPrepay(vipOrder.getOutTradeNo());
                    }
                    vipOrder.setUpdateTime(new Date());
                    vipOrder.setOrderStatus(2);
                    vipOrderService.updateVipOrder(vipOrder);
                }
            }
        }
    }
}
